<?php

namespace api\modules\app\controllers;

use api\components\BaseController;
use api\components\GeoService;
use api\modules\app\models\MetaArea;
use api\modules\app\services\MetaService;
use api\services\AreaService;
use Yii;
use api\components\Request;

class MetaDataController extends BaseController
{
    public $modelClass = '';

    public function actionEventTypes()
    {
        $userId = $this->getUser()['id'];
        return MetaService::hardcodeEventTypes();
        // return Yii::$app->eventCenter->getEventTypes($userId);
    }

    public function actionSyncArea()
    {
        $level = $this->getQuery('level', '0');
        return AreaService::sync($level);
    }

    public function actionCodeDict()
    {
        return (new MetaService())->getCodeDict();
    }

    public function actionUsers()
    {
        $query = $this->getQuery();
        return Yii::$app->dataCenter->getUsers($query);
    }

    public function actionInfoByAddress()
    {
        $params = $this->getQuery();

        return GeoService::getInfoByAddress($params);
    }

    public function actionInfoByCoord()
    {
        $params = $this->getQuery();

//        return GeoService::getInfoByCoord($params);

        return GeoService::getAreaByCoord($params);
    }



    public function actionDistrict()
    {
        return MetaArea::findAll(['category' => '区', 'status' => 1]);
    }

    public function actionStreet()
    {
        $params = $this->getQuery();
        $meta = MetaArea::findOne(['code' => $params['district_code']]);
        return MetaArea::findAll(['category' => '街道', 'status' => 1, 'parent_id' => $meta->id]);
    }

    public function actionCommunity()
    {
        $params = $this->getQuery();
        $meta = MetaArea::findOne(['code' => $params['street_code']]);
        return MetaArea::findAll(['category' => '居委','status' => 1, 'parent_id' => $meta->id]);
    }

    public function actionEstate()
    {
        $params = $this->getQuery();
        $meta = MetaArea::findOne(['code' => $params['com_code']]);
        return MetaArea::findAll(['category' => '小区', 'status' => 1, 'parent_id' => $meta->id]);
    }

    public function actionGrid()
    {
        $params = $this->getQuery();
        $meta = MetaArea::findOne(['code' => $params['street_code']]);
        return MetaArea::findAll(['category' => '网格', 'status' => 1, 'parent_id' => $meta->id]);
    }

    public function actionMdeps()
    {
        return MetaService::getManageDeps();
    }

    public function actionSyncMetaArea()
    {
        return Yii::$app->userCenter->syncMetaArea();
    }

    public function actionIot()
    {
        $params = $this->getQuery();
        $url = DATA_CENTER_USER_HOST . "/united-ciimc-api/v1/generic-query";
        $reqParams = [
            'table' => 'device',
            'limit' => $params['pageSize'],
            'offset' => (intval($params['page']) - 1) * intval($params['pageSize']),
            'token' =>  DATA_CENTER_USER_TOKEN,
            'transform' => '{"total":numHits,"messages":messages}',
            'filter' => 'exists=eq.true&isVirtual=eq.false&isSensor=eq.true&push_channel=eq.deviceCenter',
            'sort_by' => 'data.setup_time|desc'
        ];
        /** 行政区划筛选 */
        if(isset($params['meta_level6']) && !empty($params['meta_level6'])){
            $reqParams['filter'] .= '&housingEstate.rawIdentity=eq.'.$params['meta_level6'];
        }elseif (isset($params['meta_level5']) && !empty($params['meta_level5'])){
            $reqParams['filter'] .= '&neighborhoodCommittee.rawIdentity=eq.'.$params['meta_level5'];
        }elseif (isset($params['meta_level4']) && !empty($params['meta_level4'])){
            $reqParams['filter'] .= '&town.rawIdentity=eq.'.$params['meta_level4'];
        }elseif (isset($params['meta_level3']) && !empty($params['meta_level3'])){
            $reqParams['filter'] .= '&area_district.rawIdentity=eq.'.$params['meta_level3'];
        }

        /** 感知器类别筛选 */
        if (isset($params['iot_type']) && !empty($params['iot_type'])){
            $reqParams['filter'] .= '&simple.messageType=eq.' . $params['iot_type'];
        }

        /** 根据场所类别或者部件筛选是否绑定 */
        if(isset($params['bind']) && !empty($params['bind'])){
            if($params['category'] == 'unit'){
                $reqParams['filter'] .= '&component_info=ex.' . $params['bind'];
            }else {
                $reqParams['filter'] .= '&emphasis_place_info.placeType=' . ($params['bind'] == 'true' ? 'eq' : 'neq') . '.' . $params['category'];
            }
        }

        if(isset($params['deviceIds']) && !empty($params['deviceIds'])){
            $reqParams['filter'] .= '&originId=in.,'.$params['deviceIds'];
        }
        $request = new Request();
        $url = $url . '?' . http_build_query($reqParams);
        Yii::error('感知器列表请求url:'.$url);
        $response = $request->request($url, 'GET');
        Yii::error('感知器列表请求返回:'.$response);
        $response = json_decode($response,true);
        if(isset($response['result']) && $response['result'] == 'success'){
            $finalData = [];
            if(!empty($response['data']['messages'])){
                foreach ($response['data']['messages'] as $row)
                $finalData[] = [
                    'deviceId' => $row['data']['originId'],
                    'address' => $row['data']['address'],
                    'deviceTypeName' => $row['data']['messageTypeName'],
                    'setUpTime' => $row['data']['setup_time'],
                    'partCode' => isset($row['data']['component_info']['partCode']) ? $row['data']['component_info']['partCode'] : ''
                ];
            }
            return [
                'data' => $finalData,
                'total' => $response['data']['total']
            ];
        }else{
            throw new \Exception('获取感知器数据异常。');
        }
    }

    public function actionIotType()
    {
        $url = DATA_CENTER_USER_HOST . "/united-ciimc-api/v1/generic-query";
        $reqParams = [
            'table' => 'device',
            'limit' => 0,
            'filter' => 'exists=eq.true%26isVirtual=eq.false%26isSensor=eq.true%26push_channel=eq.deviceCenter',
            'token' =>  DATA_CENTER_USER_TOKEN,
            'transform' => 'aggResults."simple.messageType|messageTypeName"',
            'group_by' => 'simple.messageType|messageTypeName',
            'agg_size' => 2000
        ];
        $request = new Request();
        $url = $url . '?' . http_build_query($reqParams);
        Yii::error('感知器类别列表请求url:'.$url);
        $response = $request->request($url, 'GET');
        Yii::error('感知器类别列表请求返回:'.$response);
        $response = json_decode($response,true);
        if(isset($response['result']) && $response['result'] == "success"){
            $finalData = [];
            if(!empty($response['data'])){
                foreach ($response['data'] as $row){
                    $finalData[] = [
                        'deviceType' => $row['messageType'],
                        'deviceTypeName' => $row['messageTypeName'],
                    ];
                }
            }
            return $finalData;
        }else{
            throw new \Exception('获取感知器数据异常。');
        }
    }
}

